<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>peer</title>
    <%--<script type="text/javascript" src="https://webrtc.github.io/adapter/adapter-latest.js"></script>--%>
</head>
<h1>webRTC</h1>
<p>video</p>
<video id="localVideo" autoplay style="width: 200px;height: 200px;border: 1px red solid"></video>
<video id="remoteVideo" autoplay style="width: 200px;height: 200px;border: 1px red solid"></video>
<p></p>
<button type="button" onclick="javascript:start();">start</button>
<button type="button" onclick="javascript:createOfferAndSetLocal();">createOfferAndSetLocal</button>
<button type="button" onclick="javascript:setRemote();">setRemoteByAnswer</button>
&nbsp;&nbsp;
<button type="button" onclick="javascript:setRemoteAndCreateAnswer();">setRemoteAndCreateAnswer</button>
<button type="button" onclick="javascript:setLocal();">setLocalByOff</button>
<p>offer</p>
<input id="offer" type="textarea" style="width:300px;"></input>
<p>answer</p>
<input id="answer" type="textarea" style="width:300px;"></input>

<h1>socket</h1>
<button type="button" onclick="javascript:socketTest();">socketTest</button>

</body>

<script type="text/javascript">
    var ws = new WebSocket("ws://" + location.hostname + "/webRTCHandle");

    var localVideo = document.getElementById('localVideo');
    var remoteVideo = document.getElementById('remoteVideo');
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
    var constraints = {video: true, audio: true};

    var localStream;

    function onStartSuccess(stream) {
        localVideo.srcObject = stream;
        localStream = stream;

        localStream.getTracks().forEach(
            function (track) {
                server.addTrack(track, localStream);
            }
        );
    }

    function onStartError(error) {
        console.log("navigator.getUserMedia error: ", error);
    }

    if (navigator.getUserMedia) {

    } else {
        console.log("请使用chrome！");
    }

    var server;

    var ice = {"iceServers": [{"urls": "stun:v1.video110.cn:34780"},{
        urls: "turn:v1.video110.cn:34780",
        username: "video1",
        credential: "12wwfthisisturnserver1"
    },{"urls": "stun:v2.video110.cn:34780"},{
        urls: "turn:v2.video110.cn:34780",
        username: "video1",
        credential: "12wwfthisisturnserver1"
    },{"urls": "stun:v3.video110.cn:34780"},{
        urls: "turn:v3.video110.cn:34780",
        username: "video1",
        credential: "12wwfthisisturnserver1"
    },{"urls": "stun:v4.video110.cn:34780"},{
        urls: "turn:v4.video110.cn:34780",
        username: "video1",
        credential: "12wwfthisisturnserver1"
    },{"urls": "stun:v5.video110.cn:34780"},{
        urls: "turn:v5.video110.cn:34780",
        username: "video1",
        credential: "12wwfthisisturnserver1"
    }]};
        /*{
        "iceServers": [
            {"url": "turn:47.104.137.175:3478", "username": "gpf", "credential": "root"}
            /!*       {
              "url": "stun:stun.l.google.com:19302"
           }, {
               "url": "turn:numb.viagenie.ca",
               "username": "webrtc@live.com",
               "credential": "muazkh"
           }*!/
        ]
    };*/

    function start() {
        server = new RTCPeerConnection(ice);
        navigator.getUserMedia(constraints, onStartSuccess, onStartError);

        server.onicecandidate = function (event) {
            if (event.candidate) {
                var msg = {
                  "id": "ice",
                  "candidate": event.candidate
                }
                ws.send(JSON.stringify(msg));
            } else {
                // All ICE candidates have been sent
            }
        }

        server.onaddstream = function (event) {
            document.getElementById('remoteVideo').src = URL.createObjectURL(event.stream);
        };
    }

    var offerOptions = {
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1
    };

    function createOfferAndSetLocal() {
        server.createOffer(offerOptions).then(
            onCreateOfferSuccess,
            onCreateOfferError
        );
        server.oniceconnectionstatechange = function (e) {
            console.info("ice status ++++++++++++++" + server.iceConnectionState);
        };
        server.ontrack = gotRemoteStream;
    }

    function onCreateOfferSuccess(desc) {
        //var descString = JSON.stringify(desc);
        //console.info(descString);
        document.getElementById("offer").value = desc.sdp;
      var offer = new RTCSessionDescription({
        type: 'offer',
        sdp: desc.sdp
      });
        server.setLocalDescription(offer);
        var msg = {
          "id":"offer",
          "sdp": desc.sdp
        }
        ws.send(JSON.stringify(msg));
    }

    function onCreateOfferError(desc) {
        console.info(desc);
    }


    function setRemoteAndCreateAnswer(offerSdp) {

      server = new RTCPeerConnection(ice);
      var offer = new RTCSessionDescription({
        type: 'offer',
        sdp: offerSdp
      });
      server.setRemoteDescription(offer);


      server.onicecandidate = function (event) {
        if (event.candidate) {
          var msg = {
            "id": "ice",
            "candidate": event.candidate
          }
          ws.send(JSON.stringify(msg));
        } else {
          // All ICE candidates have been sent
        }
      }

      server.onaddstream = function (event) {
        document.getElementById('remoteVideo').src = window.URL.createObjectURL(event.stream);
      };






      navigator.getUserMedia(constraints, function(stream){

        localVideo.srcObject = stream;
        localStream = stream;

        localStream.getTracks().forEach(
            function (track) {
              server.addTrack(track, localStream);
            }
        );
        server.createAnswer().then(
            onCreateAnswerSuccess,
            onCreateAnswerError
        );
      }, onStartError);
    }

    function onCreateAnswerSuccess(answer) {
      var answer = new RTCSessionDescription({
        type: 'answer',
        sdp: answer.sdp
      });
      server.setLocalDescription(answer);
        //var descString = JSON.stringify(answer);
        document.getElementById("answer").value = answer.sdp;
        console.log(answer.sdp);
        var msg = {
          "id": "answer",
          "sdp": answer.sdp
        }
        ws.send(JSON.stringify(msg));
    }

    function onCreateAnswerError(desc) {
        console.info(desc);
    }


    function setLocal() {
        var offer = document.getElementById("offer").value;
        server.setLocalDescription(JSON.parse(offer));
    }

    function setRemote(answerSdp) {
      var answer = new RTCSessionDescription({
        type: 'answer',
        sdp: answerSdp
      });
        server.setRemoteDescription(answer);
    }

    function gotRemoteStream(e) {
        if (remoteVideo.srcObject !== e.streams[0]) {
            remoteVideo.srcObject = e.streams[0];
        }
    }


    ws.onopen = function () {
        var flag = {"event": "start", "value": ""};
        ws.send(JSON.stringify(flag));
    };

    ws.onmessage = function (evt) {
        console.info(evt.data);
        var received_msg = evt.data;
      var received_msg_Json = JSON.parse(received_msg);
        if (received_msg_Json.id==='ice') {
            try {
                server.addIceCandidate(received_msg_Json.candidate);
            } catch (e) {
                console.info(e);
            }

        } else if(received_msg_Json.id === 'offer'){
          setRemoteAndCreateAnswer(received_msg_Json.sdp);
          console.log(received_msg_Json.sdp);
        } else if(received_msg_Json.id === 'answer'){
          setRemote(received_msg_Json.sdp)
          console.log(received_msg_Json.sdp);
        }

    };

    ws.onclose = function () {
    };

    function socketTest() {
        //ws.send("测试数据试一试");
    }
</script>

</html>
